#!/bin/sh
#
#

COMMAND="${1}"
[ -z "$COMMAND" ] && COMMAND="install"

#########################################################################
#
#    Shell command 
#
#
#########################################################################

TAR=tar
CP=/bin/cp
RM=/bin/rm
GREP=grep
SED=sed
MKDIR=mkdir
CHMOD=chmod
MV=mv
CD=cd
MAKE=make
MKFS_CRAMFS=mkfs.cramfs
MKFS_JFFS2="mkfs.jffs2 -e 0x20000"
MKIMAGE=mkimage
MKNOD=mknod

#########################################################################
#
#    ANSI colors  
#
#
#########################################################################

CRE="[K"
NORMAL="[0;39m"
RED="[1;31m"
GREEN="[1;32m"
YELLOW="[1;33m"
BLUE="[1;34m"
MAGENTA="[1;35m"
CYAN="[1;36m"
WHITE="[1;37m"

#########################################################################
#
#    Path define  
#    PLATFORM : bl234x hi3510 x86
#
#########################################################################

BASE_DIR=${PWD}

ARCH=x86
#PLATFORM=bl234x
PLATFORM=x86

kshfile=/usr/bin/ksh

TOOL=${BASE_DIR}/BSP/${PLATFORM}/tool

TARGETFS=${BASE_DIR}/BSP/${PLATFORM}/targetfs

BUILD=${BASE_DIR}/build

MAMMOTH=${BASE_DIR}/DB-Like/mammoth

LITEPQ=${BASE_DIR}/libs/litepq-0.5

LIBCGICC=${BASE_DIR}/libs/libcgicc

CGI=${BASE_DIR}/UI/www

#########################################################################
#
#    Function define  
#
#
#########################################################################

ECHO()
{
	if [ -n "${2}" ];
	then 
		eval echo -n \${${2}}
	fi
	echo "${1}${NORMAL}"
}

build_DATABASE()
{
    cd ${MAMMOTH}
    make ARCH=${ARCH}
}

build_litepq()
{
    ${CD} ${LITEPQ}
    make CROSS_COMPILE=${CROSS_COMPILE}    
}

build_cgicc()
{
    ${CD} ${LIBCGICC}
    make CROSS_COMPILE=${CROSS_COMPILE}    
}

build_image()
{
	${TOOL}/mkfs.jffs2 -e 0x20000 -p -r ${TARGETFS} -b -o ${BUILD}/uJFFS2
}

build_cgi()
{
	${CD} ${CGI}
    make ARCH=${ARCH}
}


copy_cgi_to_targetfs()
{
	${CP} ${CGI}/cgi/*cgi ${TARGETFS}/www/cgi-bin
}

copy_to_targetfs()
{
    ${CP} ${LITEPQ}/libpq.so ${TARGETFS}/lib
    #${CP} ${LIBCGICC}/ ${TARGETFS}/lib
    ${CP} ${MAMMOTH}/mammoth ${TARGETFS}/bin
}

print_help()
{
	ECHO "\n    ./coral-built.sh [OPTION]\n" 		GREEN 
	ECHO "		DB"						GREEN
	ECHO "			do compile data base"		BLUE
	ECHO "		image"						GREEN
	ECHO "			do create jiffs2 image"		BLUE
	ECHO "		remove"						GREEN
	ECHO "			do remove all code\n"		BLUE
	exit 0
}


#########################################################################
#
#    Script entry 
#
#
#########################################################################

case "${COMMAND}" in

"DB")
	build_DATABASE
;;

"image")
	build_image
;;

"litepq")
	build_litepq
;;

"rootfs")
	copy_to_targetfs
;;

"cgi")
	build_cgi
;;


"cgi_install")
	copy_cgi_to_targetfs
;;

*)
	print_help
;;
esac

ECHO "\n\n	COMPLETE!!\n\n" GREEN
